﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AcadPos.Entity;
using System.Data;
using Microsoft.Reporting.WebForms;

namespace AcadPosApp.Relatorios
{
    public partial class RelatorioPreInscricao : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                carregaAreasConhecimento();
                rdbPorCurso.Checked = true;
                pnlPesquisa.Attributes.Add("onkeypress", "return clickButton(event,'" + btnConsultar.ClientID + "')");
            }
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            if(rdbPorCurso.Checked)
                carregaGridPesquisa();
            else
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Selecione Por Curso para pesquisar!', function() {});", true);
        }

        private void carregaGridPesquisa()
        {
            gvwPesquisa.Visible = true;
            Curso curso = new Curso();
            curso.Descricao = txtPesquisa.Text;
            curso.IdAreaConhecimento = Convert.ToInt32(ddlAreaConhecimento.SelectedValue);
            gvwPesquisa.DataSource = ControlClass.CNCurso.listarCursos(curso);
            gvwPesquisa.DataBind();
            gvwPesquisa.SelectedIndex = -1;
        }

        private void carregaAreasConhecimento()
        {
            AreaConhecimento area = new AreaConhecimento();
            area.Descricao = string.Empty;
            ddlAreaConhecimento.DataSource = ControlClass.CNAreaConhecimento.listarAreaConhecimento(area);
            ddlAreaConhecimento.DataTextField = "DESCRICAO";
            ddlAreaConhecimento.DataValueField = "ID_AREA_CONHECIMENTO";
            ddlAreaConhecimento.DataBind();
            ddlAreaConhecimento.Items.Insert(0, new ListItem("Todos", "0"));
        }

        protected void gvwPesquisa_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvwPesquisa.PageIndex = e.NewPageIndex;
            carregaGridPesquisa();
        }

        protected void gvwPesquisa_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            #region Configurando Imagem do Status
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[4].Visible = true;

                Image controle = (Image)e.Row.FindControl("imgStatus");
                DataRow linha = (e.Row.DataItem as DataRow);
                if ((e.Row.Cells[4].Text.Trim()) == "A")
                    controle.ImageUrl = "~/Imagens/ativo.png";
                else
                    controle.ImageUrl = "~/Imagens/inativo.png";
                e.Row.Cells[4].Visible = false;
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[4].Visible = false;
            }
            #endregion
        }

        protected void ddlAreaConhecimento_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvwPesquisa.Visible = false;
        }

        protected void gvwPesquisa_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnImprimir_Click(object sender, EventArgs e)
        {
            if (txtDtInicio.Text != "" && txtDtFim.Text != "")
            {
                Curso curso = new Curso();
                curso.IdAreaConhecimento = Convert.ToInt32(ddlAreaConhecimento.SelectedValue);
                curso.IdCurso = gvwPesquisa.SelectedIndex > -1 && gvwPesquisa.Visible == true ? Convert.ToInt32(gvwPesquisa.DataKeys[gvwPesquisa.SelectedIndex]["ID_CURSO"].ToString()) : 0;
                DateTime dtInicio = Convert.ToDateTime(txtDtInicio.Text);
                DateTime dtFim = Convert.ToDateTime(txtDtFim.Text);

                DataTable dtImp = ControlClass.CNMatricula.relatorioPreMatricula(curso, dtInicio, dtFim);
                if (dtImp.Rows.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Não há registros à serem impressos!', function() {});", true);
                }
                else
                {
                    ReportViewer ReportViewer1 = new ReportViewer();
                    ReportViewer1.Reset();
                    ReportViewer1.ProcessingMode = ProcessingMode.Local;
                    ReportViewer1.LocalReport.ReportPath = Server.MapPath(@"~/Relatorios/relatorioPreInscricao.rdlc");
                    ReportViewer1.LocalReport.DataSources.Clear();

                    string nomeCurso = gvwPesquisa.SelectedIndex > -1 && gvwPesquisa.Visible == true ? gvwPesquisa.Rows[gvwPesquisa.SelectedIndex].Cells[2].Text.ToString() : "Todos";

                    ReportParameter rp_areaConhecimento = new ReportParameter("areaConhecimento", Server.HtmlDecode(ddlAreaConhecimento.SelectedItem.Text.ToString()));
                    ReportParameter rp_curso = new ReportParameter("curso", Server.HtmlDecode(nomeCurso));
                    ReportParameter rp_dtInicio = new ReportParameter("dtInicio", Server.HtmlDecode(txtDtInicio.Text.ToString()));
                    ReportParameter rp_dtFim = new ReportParameter("dtFim", Server.HtmlDecode(txtDtFim.Text.ToString()));

                    ReportParameter[] ReportParans = new ReportParameter[] { rp_areaConhecimento, rp_curso, rp_dtInicio, rp_dtFim };
                    ReportViewer1.LocalReport.SetParameters(ReportParans);



                    ReportDataSource rds1 = new ReportDataSource();
                    rds1.Name = "DataSet1";
                    rds1.Value = dtImp;

                    ReportDataSource rds2 = new ReportDataSource();
                    rds2.Name = "DataSet2";
                    rds2.Value = ControlClass.CNParametros.getCabecalhoRelatorio();

                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(rds1);
                    ReportViewer1.LocalReport.DataSources.Add(rds2);
                    ReportViewer1.LocalReport.Refresh();

                    #region Gerar PDF
                    Warning[] warn = null;
                    string[] streamids = null;
                    string mimeType = "application/pdf";
                    string encoding = string.Empty;
                    string extension = string.Empty;
                    byte[] byteViewer;

                    byteViewer = ReportViewer1.LocalReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamids, out warn);
                    Response.Buffer = true;
                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment; filename=PreInscricao.pdf");
                    Response.BinaryWrite(byteViewer);
                    Response.Flush();

                    Response.End();
                    Response.ClearContent();
                    #endregion
                }

            }
        }

        protected void rdbTodosCursos_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbTodosCursos.Checked)
                gvwPesquisa.Visible = false;
            else
                carregaGridPesquisa();
        }

        protected void rdbPorCurso_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbPorCurso.Checked)
                carregaGridPesquisa();
            else
                gvwPesquisa.Visible = false;
        }


    }
}